package first.group.ssh.packet;

import first.group.ssh.SSHConsts;
import first.group.ssh.packet.reader.IntegerReader;
import java.nio.ByteBuffer;

public class ChannelOpenComfirmationPacket extends Packet{
    public final int recipientChannel;
    public final int senderChannel;
    public final int initialWindowSize;
    public final int maximumPacketSize;
    public final byte[] payload;

    public ChannelOpenComfirmationPacket(int recipientChannel, int senderChannel, int initialWindowSize, int maximumPacketSize, byte[] payload) {
        super(SSHConsts.SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
        this.recipientChannel = recipientChannel;
        this.senderChannel = senderChannel;
        this.initialWindowSize = initialWindowSize;
        this.maximumPacketSize = maximumPacketSize;
        this.payload = payload;
    }

    public static PacketParser<ChannelOpenComfirmationPacket> PARSER = new ChannelOpenComfirmationPacket.Parser();

    private static class Parser extends PacketParser<ChannelOpenComfirmationPacket> {

        @Override
        public ChannelOpenComfirmationPacket parse(ByteBuffer buffer) {
            var recipientChannel = IntegerReader.readInteger(buffer);
            if (recipientChannel == null) {
                return null;
            }
            var senderChannel = IntegerReader.readInteger(buffer);
            if (senderChannel == null) {
                return null;
            }
            var initialWindowSize = IntegerReader.readInteger(buffer);
            if (initialWindowSize == null) {
                return null;
            }
            var maximumPacketSize = IntegerReader.readInteger(buffer);
            if (maximumPacketSize == null) {
                return null;
            }
            var payload = new byte[buffer.remaining()];
            buffer.get(payload);
            return new ChannelOpenComfirmationPacket(recipientChannel, senderChannel, initialWindowSize, maximumPacketSize, payload);
        }
    }

    @Override
    public void write(ByteBuffer buffer) {
        buffer.putInt(recipientChannel);
        buffer.putInt(senderChannel);
        buffer.putInt(initialWindowSize);
        buffer.putInt(maximumPacketSize);
        buffer.put(payload);
    }
}
